package ${domain}.frame.validation;

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import ${domain}.frame.utils.StringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Locale;

public class SelectValidator implements ConstraintValidator<Select, String> {

    private String[] values;

    @Override
    public void initialize(Select constraintAnnotation) {
        values = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
        String fieldName = "";
        if (constraintValidatorContext instanceof ConstraintValidatorContextImpl) {
            ConstraintValidatorContextImpl validatorContext = (ConstraintValidatorContextImpl) constraintValidatorContext;
            if (validatorContext.getConstraintViolationCreationContexts() != null
                    && validatorContext.getConstraintViolationCreationContexts().size() > 0
                    && validatorContext.getConstraintViolationCreationContexts().get(0).getPath() != null) {
                fieldName = validatorContext.getConstraintViolationCreationContexts().get(0).getPath().asString();
            }
        }

        if (StringUtil.isEmpty(o)) {
            return true;
        } else {
            if (values.length == 0) {
                String message = String.format(Locale.CHINESE, "%s 指定枚举为空！", fieldName);
                constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
                return false;
            }

            int i = 0;
            for (; i < values.length; i++) {
                if (o.equals(values[i])) {
                    break;
                }
            }
            if (i < values.length) {
                return true;
            } else {
                String message = String.format(Locale.CHINESE, "%s 指定枚举组 [ %s ] 中，未找到枚举值(%s)！", fieldName, String.join(",", values), o);
                constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
                return false;
            }
        }
    }
}
